package com.lmc.chatroom.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtil {
//    设置超时时间
    private final static long EXPIRATION_DATE = 60 * 60 * 1000;
    //签名
    public static String secretString = "ND/G/LsRFDTC88R/ua9ZqGn3ueqHC5Els255MdPMiF4=";
//    对签名进行加密
    public static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    //生成令牌
    public static String getToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRATION_DATE))
                .signWith(key)
                .compact();
    }

    //解析令牌
    public static Claims parseToken(String token) {
        log.info("解析令牌"+token);
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
            body = build.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {

        } catch (Exception e) {

        }
        return body;
    }

    //校验令牌
    public static boolean checkToken(String token) {
        Claims body = parseToken(token);
        if (body == null) {
            log.info("token中的user信息为空");
            return false;
        }
        return true;
    }
}
